<template>
    <div>
        <el-container style=" border: 1px solid #eee">
            <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
                <!--            侧边导航栏-->
                <el-menu style="height: 600px" :unique-opened="false" :router="true" :default-openeds="['0','1']">
                    <el-menu-item v-if="this.showLogin" index="login">
                        <i class="el-icon-place"></i>
                        <span slot="title">登录</span>
                    </el-menu-item>
                    <el-menu-item index="game">
                        <i class="el-icon-place"></i>
                        <span slot="title">小游戏</span>
                    </el-menu-item>
                    <!--                  一级菜单-->
                    <el-submenu :default-openeds="openeds" v-for="(item,index) in menuList" :key="item.label" :index="index+''">
                        <template slot="title"><i class="el-icon-setting"></i>{{item.name}}</template>
                        <!--                        二级菜单-->
                        <el-menu-item v-for="item2 in item.children" :index="item2.path" :key="item2.label"
                                      :class="$route.path==item2.path?'is-active':''">
                            {{item2.name}}
                        </el-menu-item>
                    </el-submenu>
                </el-menu>

            </el-aside>

            <el-container>
                <el-header style="text-align: right; font-size: 12px">
                    <el-dropdown v-if="this.showDropdown">
                        <i class="el-icon-setting" style="width:50px; margin-right: 9px"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="showEditDialog">修改密码</el-dropdown-item>
                            <!--                        <el-dropdown-item>新增</el-dropdown-item>-->
                            <el-dropdown-item @click.native="logOut">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span style="font-size: 16px">欢迎回来，{{this.userInfo.userName}}</span>
                </el-header>

                <el-main>
                    <router-view></router-view>
                </el-main>
            </el-container>
        </el-container>

        <!--    修改用户信息的对话框-->
        <el-dialog
                title="修改用户密码"
                :visible.sync="editDialogVisible"
                width="50%" @close="editDialogClosed">
            <!--      内容主体区域-->
            <el-form :model="editForm" status-icon :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="用户名">
                    <el-input class="rt-input" v-model="editForm.userPhone" disabled></el-input>
                </el-form-item>
                <el-form-item label="原密码">
                    <el-input type="password" show-password v-model="editForm.password" placeholder="请输入原密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newpass">
                    <el-input type="password" show-password placeholder="请设置新密码" v-model="editForm.newPwd"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input type="password" show-password @keyup.enter.native="editPwds" placeholder="请确认新密码"
                              v-model="editForm.checkPass" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
          <el-button @click="resetEdit">重置修改</el-button>
          <el-button type="primary" @click="editPwds">确定修改</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<style>
    .el-header {
        background-color: #B3C0D1;
        color: #333;
        line-height: 60px;
    }

    .rt-input /deep/ .el-input__inner {
        color: #6B6C70 !important;
        cursor: pointer;
    }

    /*html,body,#app{*/
    /*    height: 90%;*/

    /*}*/

    .el-aside {
        color: #333;
    }
</style>

<script>

    import AllExams from "./admin/AllExams";

    export default {
        data() {
            // 密码校验
            var Pass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入新密码'))
                } else {
                    callback()
                }
            }
            var Pass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.editForm.newPwd) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            return {
                menuList: [],
                //  管理员菜单

                openeds: ['5'],
                adminMenuList: [
                    {
                        path: '/',
                        name: '信息管理',
                        children: [
                            {
                                path: '/sort',
                                name: '分类信息',
                            },
                            {
                                path: '/garbage',
                                name: '垃圾信息',
                            }
                        ]
                    },
                    {
                        path: '/navigation',
                        name: '问卷信息',
                        children: [
                            {
                                path: '/statics',
                                name: '题目统计',
                            },
                            {
                                path: '/allExams',
                                name: '问卷统计',
                            }
                        ]
                    },
                    {
                        path: "/navigation",
                        name: "用户管理",
                        children: [
                            {
                                path: '/checkUsers',
                                name: '用户审核',
                            }
                        ]
                    }

                ],
                //  用户菜单
                userMenuList: [
                    {
                        path: "/navigation",
                        name: "我的信息",
                        children: [
                            {
                                path: '/userInfo',
                                name: '个人信息',
                            }
                        ]
                    },
                    {
                        path: "/navigation",
                        name: "问卷调查",
                        children: [
                            {
                                path: '/createExam',
                                name: '回答问卷',
                            },
                            {
                                path: '/myExams',
                                name: '我的问卷'
                            }
                        ]
                    }
                ],
                //  用户信息
                userInfo: [],
                //  是否显示登录按钮
                showLogin: false,
                showDropdown: true,
                editDialogVisible: false,
                // 查询到的用户密码信息
                editForm: {
                    userPhone: '',
                    password: '',
                    newPwd: '',
                    checkPass: ''
                },
                editFormRules: {
                    newPwd: [
                        {
                            require: true,
                            message: '密码不能为空',
                            trigger: 'blur'
                        },
                        {
                            min: 8,
                            max: 20,
                            message: '密码长度不少于8位',
                            trigger: 'blur'
                        },
                        {
                            validator: Pass,
                            trigger: 'blur'
                        }
                    ],
                    checkPass: [
                        {
                            require: true,
                            message: '确认新密码不能为空',
                            trigger: 'blur'
                        },
                        {
                            min: 1,
                            max: 20,
                            message: '密码长度不少于6位',
                            trigger: 'blur'
                        },
                        {
                            validator: Pass2,
                            trigger: 'blur'
                        }
                    ]
                }
            }

        },
        created() {
            this.checkToken();
            this.getUserinfo();
            this.getMenuList();
        },
        methods: {
            // 验证token是否失效
            async checkToken() {
                const {data: res} = await this.$http.get('/user/verify/')
                console.log(res)
                if (res.status !== 200) {
                    window.sessionStorage.clear()
                    sessionStorage.clear()
                    localStorage.clear()
                }
            },
            getMenuList() {
                if (localStorage.getItem('role')!=null){
                    if (localStorage.getItem('role') === 'user') {
                        this.menuList = this.userMenuList
                        this.showLogin = false
                    } else if (localStorage.getItem('role') === 'admin') {
                        this.menuList = this.adminMenuList
                        this.showLogin = false
                    } else {
                        this.showLogin = true
                        this.menuList = null
                    }
                }
                else {
                    if (sessionStorage.getItem('role') === 'user') {
                        this.menuList = this.userMenuList
                        this.showLogin = false
                    } else if (sessionStorage.getItem('role') === 'admin') {
                        this.menuList = this.adminMenuList
                        this.showLogin = false
                    } else {
                        this.showLogin = true
                        this.menuList = null
                    }
                }

            },

            // async login() {
            //     const {data: res} = await this.$http.post('/user/login', {
            //         userPhone: "18888888888",
            //         password: "E9BC0E13A8A16CBB07B175D92A113126",
            //     })
            //     console.log(res)
            //     localStorage.setItem('token', 'Bearer ' + res.data.token)
            //     localStorage.setItem('username', res.data.phone)
            //     localStorage.setItem('role', res.data.role)
            // },
            // 获取用户信息
            async getUserinfo() {
                let role
                let username
                if (localStorage.getItem('role')!=null){
                    role = localStorage.getItem('role')
                    username = localStorage.getItem('username')
                }else{
                    role = sessionStorage.getItem('role')
                    username = sessionStorage.getItem('username')
                }

                if (role === 'user') {
                    const {data: res} = await this.$http.get('/user/showInfo/' + username)
                    console.log(res)
                    if (res.status !== 200) return this.$message.error(res.msg)
                    this.userInfo = res.data
                    // console.log(this.userInfo.userPhone)
                    // this.editForm.userPhone = this.userInfo.userPhone
                    localStorage.setItem('name', res.data.userName)
                } else if (role === 'admin') {
                    const {data: res} = await this.$http.get('/user/showInfo/' + username)
                    console.log(res)
                    if (res.status !== 200) return this.$message.error(res.msg)
                    this.userInfo = res.data
                    // console.log(this.userInfo.userPhone)
                    // this.editForm.userPhone = this.userInfo.userPhone
                    localStorage.setItem('name', res.data.userName)
                } else {
                    this.userInfo.userName = '游客'
                    this.showDropdown = false
                }
            },
            // 监听修改密码对话框的关闭事件
            editDialogClosed() {
                this.editForm.password = ''
                this.$refs.editFormRef.resetFields()
            },
            // 点击按钮，修改用户密码
            resetEdit() {
                this.editForm.password = '',
                this.editForm.newPwd = '',
                this.editForm.checkPass = ''
            },
            editPwds() {
                if ((this.editForm.newPwd.length < 8) || !(/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/.test(this.editForm.newPwd))) {
                    return this.$message.error('新密码不合法，请检查!!')
                }
                this.$refs.editFormRef.validate(async valid => {
                    // console.log(valid)
                    if (!valid) return
                    const {data: res} = await this.$http.put('/user/updatePwd', {
                        userPhone: this.editForm.userPhone,
                        password: this.$md5(this.editForm.password).toUpperCase(),
                        newPwd: this.$md5(this.editForm.newPwd).toUpperCase()
                    })
                    console.log(res)
                    if (res.status !== 200) {
                        return this.$message.error(res.msg + '，更新用户密码失败!')
                    }
                    this.$message.success('更新用户密码成功！')
                    this.editDialogVisible = false
                })
            },
            showEditDialog() {
                this.editForm.userPhone = this.userInfo.userPhone
                this.editDialogVisible = true
            },
            // 修改垃圾信息
            logOut() {
                this.$confirm('是否退出登录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    window.sessionStorage.clear()
                    sessionStorage.clear()
                    localStorage.clear()
                    // this.$forceUpdate()
                    // this.$router.push({ path: '/' + new Date() });
                    this.$router.push('/')
                    this.$router.go(0)
                    this.$message({
                        type: 'success',
                        message: '退出成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });


            }
        }
    };
</script>
